<template>
  <div class="certification-form">
    <el-form :model="form" :rules="rules" ref="formRef" label-width="120px">
      <!-- 基础信息 -->
      <el-form-item label="考证名称" prop="bkzname">
        <el-input v-model="form.bkzname" placeholder="请输入"></el-input>
      </el-form-item>

      <el-form-item label="报名截止时间" prop="bkzbmenddate">
        <el-date-picker
          v-model="form.bkzbmenddate"
          type="datetime"
          placeholder="请选择"
          style="width: 680px"
        ></el-date-picker>
      </el-form-item>

      <el-form-item label="考试时间" prop="bkzksdate">
        <el-date-picker
          v-model="form.bkzksdate"
          type="datetime"
          placeholder="请选择"
          style="width: 680px"
        ></el-date-picker>
      </el-form-item>

      <!-- 报考城市 -->
      <el-form-item label="报考城市" prop="bkzcbkcs">
        <el-input v-model="form.bkzcbkcs" placeholder="请输入"></el-input>
      </el-form-item>

      <!-- 考证职业 -->
      <el-form-item label="考评职业：" prop="bkzkpzy">
        <el-select
          v-model="form.bkzkpzy"
          placeholder="请选择"
          style="width: 100%"
        >
          <el-option
            v-for="item in bkzkpzy"
            :key="item"
            :label="item"
            :value="item">
          </el-option>
        </el-select>
      </el-form-item>

      <!-- 考证等级设置  -->
      <el-form-item label="考评等级设置：" prop="user_dev" >
        <el-button
          type="primary"
          @click="addLevel"
          icon="el-icon-plus"
        >添加等级</el-button>
        <label>注：福利课程，题库仅再赠送给参加培训的学员</label>
      </el-form-item>

      <!-- 动态等级设置 -->
      <div class="level-head">
        <div v-for="(level, index) in form.bkzlevelitems" :key="index" class="level-item">
          <div class="level-title">
            <el-form-item label="考评等级" label-width="80px">
              <el-select v-model="level.kzllevelname" placeholder="请选择" clearable style="width: 90px">
                <el-option
                  v-for="item in courses"
                  :key="item"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-button
              type="text"
              @click="removeLevel(index)"
              icon="el-icon-delete"
            >删除</el-button>
          </div>

          <el-form-item label="考试价格" prop="name" class="required-item" label-width="80px">
            <el-input v-model="level.kzlprice" placeholder="请输入" style="width: 200px"></el-input>元
          </el-form-item>
          <el-form-item label="福利课程" label-width="80px">
            <el-select v-model="level.flkc" placeholder="请选择" multiple  clearable>
              <el-option
                v-for="item in publicCourse"
                :key="item.bc_code"
                :label="item.bc_name"
                :value="item.bc_code"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="福利题库" label-width="80px">
            <el-select v-model="level.fltk" placeholder="请选择" multiple clearable>
              <el-option
                v-for="item in tiku"
                :key="item.btk_code"
                :label="item.btk_name"
                :value="item.btk_code"
              ></el-option>
            </el-select>
          </el-form-item>

          <div class="level-foot">
            <el-form-item label="可选培训" label-width="80px">
              <el-checkbox v-model="level.kzlfortrain">提供培训</el-checkbox>
              <!--            <el-input-number-->
              <!--              v-model="level.trainingPrice"-->
              <!--              :min="0"-->
              <!--              :disabled="!level.hasTraining"-->
              <!--              style="margin-left: 10px;"-->
              <!--            ><template v-slot="append">元</template></el-input-number>-->
            </el-form-item>
            <el-form-item label="价格" prop="name" label-width="60px">
              <el-input v-model="level.kzlfortrainprice" :disabled="!level.kzlfortrain" placeholder="请输入" style="width: 80px"></el-input>元
            </el-form-item>
          </div>
        </div>
      </div>

      <!-- 分佣方式 -->
<!--      <el-divider>分销分佣</el-divider>-->
      <el-form-item label="分佣方式">
        <el-radio-group v-model="form.commissionType">
          <el-radio label="ratio">商品金额比例分佣
            <el-input :disabled="form.commissionType !='ratio'" v-model="form.bkzpercentprice" placeholder="请输入" style="width: 80px"></el-input>%
          </el-radio>
          <el-radio label="fixed">固定金额分佣
            <el-input :disabled="form.commissionType !='fixed'" v-model="form.bkzgdprice" placeholder="请输入" style="width: 80px"></el-input>元
          </el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 封面 -->
      <el-form-item label="封面：">
        <div>
          <el-upload
            class="avatar-uploader"
            action="#"
            :auto-upload="false"
            :on-change="changeavart"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="courseLogo" :src="courseLogo" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </div>
        <div class="upload-tip">展示于列表和详情页。图片小于1M。
          建议上传 3:4 比例（如750x1000px）的JPG/PNG/WebP格式。</div>
      </el-form-item>
      <!-- 考证介绍 -->
      <el-form-item label="考证介绍：" prop="user_phoneno" >
        <el-input
          v-model="form.bkzkzjsdesc"
          placeholder="请输入"
          clearable
          type="textarea"
          rows="10"
        ></el-input>
      </el-form-item>
      <!-- 团队优惠政策 -->
      <el-form-item label="团队优惠政策：" prop="user_phoneno" >
        <el-input
          v-model="form.bkztdyhzcdesc"
          placeholder="请输入"
          clearable
          type="textarea"
          rows="10"
        ></el-input>
      </el-form-item>
      <!-- 等级申报条件 -->
      <el-form-item label="等级申报条件：" prop="user_phoneno" >
        <el-input
          v-model="form.bkzdjsbtjdesc"
          placeholder="请输入"
          clearable
          type="textarea"
          rows="10"
        ></el-input>
      </el-form-item>

      <!-- 提交按钮 -->
      <el-form-item>
<!--        <el-button type="primary" @click="saveBut">仅保存</el-button>-->
        <el-button type="primary" @click="submitForm('edit')">保存提交</el-button>
        <el-button type="primary" @click="cancleBut">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import {createkz, querybtklist, querycblist, querydict, updatekz, uploadres} from "../../api/InstitutionApi";
import { formatDate } from "../../utils/util"

export default {
  data() {
    return {

      form: {
        bkzname: '', ///考证名称
        bkzbmenddate: '', ///报名截止时间
        bkzksdate: '', ///考试时间
        bkzcbkcs:'', //报考城市
        bkzkpzy: '', ///考证职业
        bkzlevelitems: [
          {
            kzllevelname: '四级', ///考证等级
            kzlprice: '',  ///考试价格
            flkc: [],  ///福利课程
            fltk: [], ///福利题库
            kzlfortrain: false, ///是否提供培训
            kzlfortrainprice: ''  ////培训价格
          }
        ],
        commissionType: 'ratio', ///分佣方式
        bkzpercentprice: 0 , ///金额分佣比例
        bkzgdprice: 0, //固定金额分佣元
        apiImgLogoCode: '', ////上传封面图片的code
        bkzkzjsdesc: '', ///考证介绍
        bkztdyhzcdesc: '', ////团队优惠政策
        bkzdjsbtjdesc: '' ///等级申报条件
      },
      //封面图片url
      // bkzlogouri: '',  ///上传图片
      courseLogo: '', ///主要用于显示上传图片的缩略图
      base64Data: '', ///保存图片转base64
      // 编辑时当前考证的code
      currentCode: '',
      // 提交时用的
      submitFormData: {},
      rules: {
        bkzname: [{ required: true, message: '请输入考证名称', trigger: 'blur' }],
        bkzbmenddate: [{ required: true, message: '请选择截止时间', trigger: 'change' }],
        bkzksdate: [{ required: true, message: '请选择考试时间', trigger: 'change' }],
        kzlprice: [{ required: true, message: '请输入价格', trigger: 'blur' }]
      },
      // 字典项
      dictNode: [], ///字典根项
      tmpItem: {},
      // 考证职业
      bkzkpzy: [],
      // 考证等级
      courses: [],
      // 福利课程
      flcouse: [
        { id: 1, name: '康养课' },
        { id: 2, name: '营养课' },
        { id: 3, name: '风水课' },
        { id: 4, name: '走路课' },
      ],
      // 题库
      tiku: [],
      isEdit: false,
    }
  },
  computed: {
     //  只返回发布的在线课程
    publicCourse() {
      return this.flcouse.filter(item => item.bc_publishstate === 1 )
    }

  },
  created() {
     // 通过接口初始化数据
  //   调用福利题库
    this.getTkList()
  //   获取所有在线课程
    this.getOnlineCourse()
    // 编辑进的处理
    setTimeout(() => {
      if(this.$route.query.rowData) {
        this.isEdit = true
        this.submitFormData = {}
        this.submitFormData = this.$route.query.rowData;
        // console.log('编辑传值 ',this.submitFormData )
        // 若有值表示是编辑传递值
        this.rowToForm();
        //   加载字典项

      } else {
        this.isEdit = false
      }
    },800)
    // 获取字典根项
    this.selectdictNode()
  },
  methods: {
    // 查询所有题库列表
    getTkList() {
      querybtklist().then(res => {
        this.tiku =[]
        this.tiku = res.data.base_info;
        console.log('获取所有题库列表：', this.tiku)
      })
    },
    // 获取在线课程
    getOnlineCourse() {
      // 获取课程基础信息列表
      querycblist({
      }).then(res => {
        this.flcouse = []
        this.flcouse = res.data.base_info
        console.log('获取在线课程列表：', this.flcouse)
      })
    },

    // 查询字典开始
    selectdictNode() {
      querydict({
        "dictcode": "0"
      }).then(res => {
        console.log('根项字典', res)
        this.dictNode = []
        this.dictNode = res.data.data.base_info
        this.selectItem()
      })
    },
    // 查询字典项
    async selectItem() {
      this.bkzkpzy = []
      this.levels = []
      // 考证职业
      this.tmpItem = {}
      this.tmpItem = this.dictNode.filter(item => item.dict_name === '考评职业')
      let returnItemjobName = []
      returnItemjobName = await this.selectItemApi(this.tmpItem[0].dict_code)

      for (let i = 0; i < returnItemjobName.length; i++) {
        this.bkzkpzy.push(returnItemjobName[i].dict_name)
      }

      // 考评等级
      this.tmpItem = {}
      this.tmpItem = this.dictNode.filter(item => item.dict_name === '考评等级')
      let returnItemjobClassfiy = []
      returnItemjobClassfiy = await this.selectItemApi(this.tmpItem[0].dict_code)
      for (let i = 0; i < returnItemjobClassfiy.length; i++) {
        this.courses.push(returnItemjobClassfiy[i].dict_name)
      }
      // console.log('tmpItem-1:', this.bkzkpzy, this.courses);
    },

    selectItemApi(itemcode) {
      return querydict({
        "dictcode": itemcode
      }).then(res => res.data.data.base_info)
    },
    // 查询字典结束


    // 等级选项状态处理
    levelStatus() {
      // 新等级设置内的是否培状态变成0或1
      for(let i=0; i<this.form.bkzlevelitems.length; i++) {
        console.log('提交-真假：', this.form.bkzlevelitems[i].kzlfortrain)
        if (this.form.bkzlevelitems[i].kzlfortrain === 1) {
          this.form.bkzlevelitems[i].kzlfortrain = true
        } else {
          this.form.bkzlevelitems[i].kzlfortrain = false
        }
      }
      // console.log('状态变化：', this.form)
    },
    // 编辑时进行值的赋值
    rowToForm() {
      let levelitems = []
      let bkzlevels = this.submitFormData.bkz_levels
      for(let i=0; i<bkzlevels.length; i++) {
        console.log('赋值完成-1：',this.form)
        levelitems.push({
          kzllevelname: bkzlevels[i].kzl_levelname, ///考证等级
          kzlprice: bkzlevels[i].kzl_price,  ///考试价格
          flkc: this.editGetFl(bkzlevels[i].kcfl,'kcfl'),  ///福利课程
          fltk: this.editGetFl(bkzlevels[i].tkfl,'tkfl'), ///福利题库
          kzlfortrain: String(bkzlevels[i].kzl_fortrain) === '0' ? false : true, ///是否提供培训
          kzlfortrainprice: bkzlevels[i].kzl_fortrainprice////培训价格
        })
      }
      this.currentCode = this.submitFormData.bkz_code
      this.form = {
        bkzname : this.submitFormData.bkz_name,
        bkzbmenddate : this.submitFormData.bkz_bmenddate,
        bkzksdate : this.submitFormData.bkz_ksdate,
        bkzcbkcs: this.submitFormData.bkz_bkcs,//报考城市
        bkzkpzy: this.submitFormData.bkz_kpzy, ///考证职业
        commissionType: this.submitFormData.bkz_percentprice !== ''? 'ratio':'fixed', ///分佣方式
        bkzpercentprice: this.submitFormData.bkz_percentprice,///金额分佣比例
        bkzgdprice: this.submitFormData.bkz_gdprice,//固定金额分佣元
        apiImgLogoCode: this.submitFormData.bkz_logo_uri[0].imguri,  ///上传图片code
        bkzkzjsdesc: this.submitFormData.bkz_kzjs_desc, ///考证介绍
        bkztdyhzcdesc: this.submitFormData.bkz_tdyhzc_desc,  ////团队优惠政策
        bkzdjsbtjdesc: this.submitFormData.bkz_djsbtj_desc, ///等级申报条件
        bkzlevelitems: levelitems
      }
      this.courseLogo = this.submitFormData.bkz_logo_uri[0].url
      // this.form.bkzlevelitems = []
      // console.log('赋值完成：',this.form, this.currentCode)
    },
    // 编辑获取福利课程与福利题库
    editGetFl(item,type) {
      console.log('item项:',item)
      let tmpEditFl = []
      for(let i=0; i<item.length; i++) {
        tmpEditFl.push(item[i].kzlfl_rescode)
      }
      // 去掉不存在的福利
      if(type === 'kcfl') {
      //   课程福利
      //   for(let i=0; i<item.length; i++) {
      //     for(let j=0; j<this.flcouse.length; j++) {
      //       console.log('item项-3:',this.flcouse,this.flcouse[j].bc_code,item[i].kzlfl_rescode)
      //       if(this.flcouse[j].bc_code === item[i].kzlfl_rescode) {
      //         console.log('item项-2:',this.flcouse[j].bc_code,item[i].kzlfl_rescode)
      //         tmpEditFl.push(item[i].kzlfl_rescode)
      //       }
      //     }
      //   }
        tmpEditFl = tmpEditFl.filter(item => this.flcouse.some(course => course.bc_code === item));
      } else {
      //   题库福利
        tmpEditFl = tmpEditFl.filter(item => this.tiku.some(course => course.btk_code === item));
      }
      console.log('item项-1:',tmpEditFl)
      return tmpEditFl
    },

    // 添加等级
    addLevel() {
      // const nextGrade = this.gradeOptions[this.form.levels.length];
      // if (!nextGrade) {
      //   this.$message.warning('已添加所有等级');
      //   return;
      // }
      this.form.bkzlevelitems.push({
        kzllevelname: '四级', ///考证等级
        kzlprice: '',  ///考试价格
        flkc: [],  ///福利课程
        fltk: [], ///福利题库
        kzlfortrain: false, ///是否提供培训
        kzlfortrainprice: ''  ////培训价格
      });
    },

    // 删除等级
    removeLevel(index) {
      if (this.form.bkzlevelitems.length <= 1) {
        this.$message.warning('至少保留一个等级');
        return;
      }
      this.form.bkzlevelitems.splice(index, 1);
    },

    /////封面处理
    // 自定义上传方法
    customUpload(type) {
      uploadres({
        "usercode": localStorage.getItem('usercode'), //#用户标识号
        "rescode": this.base64Data,//#图片资源的base64码
        "restype":"0",//#资源类型，0企业营业执照，1企业logo，2门头照，3企业环境,4个人简介视频
        "resdesc": type  //图片描述"
      }).then(res => {
        console.log('图片上传：',res)
        this.form.apiImgLogoCode = res.data.base_info
      })
    },

    // 上传前将图片转为base64
    beforeUpload(file,type) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => {
          // 方法1：直接使用完整的DataURL（推荐）
          this.courseLogo = reader.result; // 带前缀的完整Base64，可直接用于<img>显示
              // this.form.courseimgUrl = reader.result; // 带前缀的完整Base64，可直接用于<img>显示
          // 方法2：如果需要纯Base64（去掉前缀）
          const pureBase64 = reader.result.split(',')[1];
          this.base64Data = pureBase64;

          // console.log('完整DataURL:', reader.result);
          // console.log('纯Base64:', pureBase64);

          resolve(true); // 必须返回true才会继续上传
          this.customUpload(type)
        };
        reader.onerror = error => {
          console.error('文件读取失败:', error);
          reject(error);
        };
      });
    },

    changeavart(file){
      console.log('头像：',file);
      this.beforeUpload(file.raw,'logo')
    },
    handleAvatarSuccess(res, file) {
      this.courseLogo = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      console.log('上传格式：',file);
      const isJPG = file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 png 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },

    /////封面处理结束


    // 仅保存
    saveBut() {
      console.log('仅保存：', this.form)
    },
    // 取消
    cancleBut() {
      this.$router.push({
        path: '/item/item',
        query: ''
      });
    },
    // 表单提交
    submitForm() {
      // 深拷贝才可以不互相影响，不影响原来的fom
      this.submitFormData = {}
      this.submitFormData = JSON.parse(JSON.stringify(this.form));
      // 新等级设置内的是否培状态变成0或1
      for(let i=0; i<this.submitFormData.bkzlevelitems.length; i++) {
        console.log('提交-真假：', this.submitFormData.bkzlevelitems[i].kzlfortrain)
        if(this.submitFormData.bkzlevelitems[i].kzlfortrain) {
          this.submitFormData.bkzlevelitems[i].kzlfortrain = 1
        } else {
          this.submitFormData.bkzlevelitems[i].kzlfortrain = 0
        }
      }
      console.log('提交：', this.submitFormData)
      this.$refs.formRef.validate(valid => {
        if (valid) {
          if(this.isEdit) {
            updatekz({
              "bkzcode": this.currentCode,   ///#考证code
              "bkzname": this.submitFormData.bkzname, //#考证名称
              "bkzbmenddate": formatDate(this.submitFormData.bkzbmenddate),//#报名截止时间
              "bkzksdate": formatDate(this.submitFormData.bkzksdate),//#考试时间
              "bkzcbkcs": this.submitFormData.bkzcbkcs,//#报考城市
              "bkzkpzy": this.submitFormData.bkzkpzy,//#考评职业
              "bkzlevelitems":this.submitFormData.bkzlevelitems,//#考评等级项[]
              "bkzpercentprice": this.submitFormData.bkzpercentprice,//#商品分佣百分比
              "bkzgdprice": this.submitFormData.bkzgdprice,//#商品分佣固定价格
              "bkzlogouri":this.submitFormData.apiImgLogoCode,//#logo图片uri
              "bkzkzjsdesc": this.submitFormData.bkzkzjsdesc,//#考证介绍
              "bkztdyhzcdesc": this.submitFormData.bkztdyhzcdesc,//#团队优惠政策
              "bkzdjsbtjdesc": this.submitFormData.bkzdjsbtjdesc,//#等级申报条件
            }).then(res => {
              console.log('编程课程：',res)
              this.$message.success('编辑成功');
              if(res.data.bkzode !== '') {
                this.$router.push({
                  path: '/item/item',
                  query: ''
                });
              }
            }).catch(err => {

            })

          } else {
            // 创建
            createkz({
              "bkzname": this.submitFormData.bkzname, //#考证名称
              "bkzbmenddate": formatDate(this.submitFormData.bkzbmenddate),//#报名截止时间
              "bkzksdate": formatDate(this.submitFormData.bkzksdate),//#考试时间
              "bkzcbkcs": this.submitFormData.bkzcbkcs,//#报考城市
              "bkzkpzy": this.submitFormData.bkzkpzy,//#考评职业
              "bkzlevelitems":this.submitFormData.bkzlevelitems,//#考评等级项[]
              "bkzpercentprice": this.submitFormData.bkzpercentprice,//#商品分佣百分比
              "bkzgdprice": this.submitFormData.bkzgdprice,//#商品分佣固定价格
              "bkzlogouri":this.submitFormData.apiImgLogoCode,//#logo图片uri
              "bkzkzjsdesc": this.submitFormData.bkzkzjsdesc,//#考证介绍
              "bkztdyhzcdesc": this.submitFormData.bkztdyhzcdesc,//#团队优惠政策
              "bkzdjsbtjdesc": this.submitFormData.bkzdjsbtjdesc,//#等级申报条件
            }).then(res =>{
              console.log('提交课程：',res)
              this.$message.success('添加成功');
              if(res.data.bkzode !== '') {
                this.$router.push({
                  path: '/item/item',
                  query: ''
                });
              }
            })
          }
          // console.log('提交数据:', submitData);

        } else {
          this.$message.error('请检查表单');
          return false;
        }
      });
    }
  }
}
</script>
<style scoped>
.certification-form {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.level-head {
  display: flex;
}

.level-item {
  width: 350px;
  margin-right: 10px;
  margin-bottom: 30px;
  border: 1px solid #ebeef5;
  padding: 5px;
  border-radius: 4px;
}

.level-title {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.level-foot {
  display: flex;
  justify-content: flex-start;
}


.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 150px;
  height: 150px;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  line-height: 150px;
  text-align: center;
}

.avatar {
  width: 100%;
  height: 100%;
  display: block;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 10px;
}
</style>
